//
//  JKRAudioToll.m
//  AudioServersDemo
//
//  Created by Lucky on 15/10/7.
//  Copyright © 2015年 Lucky. All rights reserved.
//

#import "JKRAudioToll.h"
#import <AVFoundation/AVFoundation.h>

@implementation JKRAudioToll

static NSMutableDictionary *_soundIDs;

+ (NSMutableDictionary *)soundIDs
{
    if (!_soundIDs) {
        _soundIDs = [NSMutableDictionary dictionary];
    }
    return _soundIDs;
}

+ (void)playAudioWithFileName:(NSString *)fileName
{
    if (fileName == nil) {
        return;
    }
    
    SystemSoundID soundID = [[self soundIDs][fileName] unsignedIntValue];
    
    if (!soundID) {
        NSURL *url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
        
        if (!url) {
            return;
        }
        
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
        
        [self soundIDs][fileName] = @(soundID);
    }
    
    AudioServicesPlaySystemSound(soundID);
}

+ (void)disposeAudioWithFileName:(NSString *)fileName
{
    if (!fileName) {
        return;
    }
    
    SystemSoundID soundID = [[self soundIDs][fileName] unsignedIntValue];
    
    if (soundID) {
        AudioServicesDisposeSystemSoundID(soundID);
        
        [[self soundIDs] removeObjectForKey:fileName];
    }
}

@end
